<template>
  <div>
    <page-header-wrapper></page-header-wrapper>
    <a-card style="margin-top: 20px">
      <div class="table-page-search-wrapper">
        <a-form :form="searchForm" layout="inline">
          <a-row :gutter="48">
            <SearchFormItems
              :searchKeys="ClientListSearchKeys"
              :advanceVal="advanced"
              :getDataWithKey="getDataWithKey"
            >
            </SearchFormItems>
            <a-col :md="(!advanced && 8) || 6" :sm="6" class="advanced_butns">
              <span
                class="table-page-search-submitButtons"
                :style="
                  (advanced && { float: 'right', overflow: 'hidden' }) || {}
                "
              >
                <a-button @click="reset">重置</a-button>
                <a-button type="primary" @click="search">查询</a-button>
                <a @click="toggleAdvanced">
                  {{ advanced ? "收起" : "展开" }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <div class="cont_box">
      <div class="table_header flex-between">
        <div class="table_name">{{ pageTitle }}</div>
        <div class="table_butns flex-end">
          <a-button type="primary" icon="plus" @click="showModal('add', null)"
            >新增</a-button
          >
        </div>
      </div>
      <a-table
        :columns="ClientListColumn"
        :dataSource="dataSource"
        :pagination="pagination"
        :rowKey="(it) => it.id"
        :loading="loading"
        binvested
        @change="tableSort"
        :expandedRowKeys="curExpandedRowKeys"
        @expand="getInnerData"
      >
        <div slot="expandedRowRender" slot-scope="record">
          <a-spin :spinning="importLoading">
          <a-table
            :columns="ClientExpandColumn"
            :dataSource="innerData"
            :pagination="false"
            :rowKey="(it) => it.id"
            :loading="innerLoading"
          >
          <template slot="operation" slot-scope="innerTex">
            <a-button type="primary" @click="editTem(innerTex)">编辑</a-button>
            <a-upload class="uploadExcel" style="margin:0 10px;" 
              :show-upload-list="false" maxCount="1" accept="xlsx,xls" 
              :data="{templateId:innerTex.id,clientId:record.id}" 
              :customRequest="customUploadExcel"
            >
              <a-button type="default">导入Excel</a-button>
            </a-upload>
            <a-button type="danger" @click="deleteTem(innerTex)">删除</a-button>
          </template>
          </a-table>
        </a-spin>
        </div>
        <a-badge
          slot="status"
          slot-scope="text"
          :status="text.status == 1 ? 'success' : 'error'"
          :text="text.status == 1 ? '正常' : '禁用'"
        />
        <span slot="operation" slot-scope="text, record">
          <a-button size="small" type="link" @click="statusUpdate(record)">
            {{ text.status == 1 ? "禁用" : "启用" }}
          </a-button>
          <a-button size="small" type="link" @click="showModal('edit', record)">
            编辑
          </a-button>
          <a-button size="small" type="link" @click="createNewTem(record)">
            新增模板
          </a-button>
          <a-button size="small" type="link" @click="goSkuPrice(record)">
            一客一价
          </a-button>
          <a-button size="small" type="link" @click="checkGoogleAuth(record)">
            查看Google授权
          </a-button>
          <a-button size="small" type="link" @click="showGoogleModal(record)">
            Google授权
          </a-button>
        </span>
      </a-table>
      <pagination
        :total="total"
        :page.sync="page"
        :size.sync="size"
        :onPageSizeChange="onPageSizeChange"
      />
      <a-modal
        :title="modalType == 'edit' ? '编辑' : '新增'"
        v-model="editVisible"
        destroyOnClose
        @ok="sureModal"
        width="600px"
      >
        <div class="modal_body_cont">
          <a-form
            :form="modalForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
          >
            <modalFormItem
              :searchKeys="ClientModalKeys"
              :getDataWithKey="getDataWithKey"
            ></modalFormItem>
          </a-form>
        </div>
      </a-modal>
      <a-modal
        :title="templateType == 'edit' ? '编辑模板' : '新增模板'"
        v-model="templateVisible"
        destroyOnClose
        @ok="sureTemplate"
        width="600px"
        :bodyStyle="{height:'500px',overflowY:'auto'}"
      >
        <div class="modal_body_cont">
          <a-form layout="inline" style="margin-bottom: 15px;">
            <a-form-item label="模板名称" required>
              <a-input v-model="templateName"  :style="{width:'400px'}" placeholder="请输入模板名称" />
            </a-form-item>
          </a-form>
          <table class="my-table">
            <thead>
              <tr>
                <th>工厂字段</th>
                <th>客户字段</th>
                <th>是否必填</th>
              </tr> 
            </thead>
              <tbody>
              <tr v-for="(item,index) in FieldList" :key="index">
                <td>
                  <a-popover title="">
                    <template slot="content">
                      <p>{{ item.cnName }}</p>
                    </template>
                    <div>{{item.field}}</div>
                  </a-popover>
                  <!-- <div v-else>{{ item.field }}</div> -->
                </td>
                <td>
                  <template>
                    <a-input v-model="item.replaceField"  :style="{width:'215px'}" placeholder="请输入值" />
                  </template>
                </td>
                <td>{{item.isRequire? '必填':'非必填'}} </td>
              </tr>
            </tbody>
          </table>
        </div>
      </a-modal>
      <a-modal
        title="谷歌授权信息"
        v-model="googleVisible"
        destroyOnClose
        width="500px"
        :footer="null"
      >
        <div class="modal_body_cont">
          <a-table
            :columns="ClientGoogleListColumn"
            :dataSource="googleList"
            :pagination="false"
            :rowKey="(it,index) => index"
            :loading="loading"
            binvested
          >
          </a-table>
        </div>
      </a-modal>
      <a-modal
        title="谷歌邮箱"
        v-model="validEmailVisible"
        destroyOnClose
        width="600px"
        @ok="sureGoogleEmail"
        @cancel="cancelGoogleEmail"
      >
        <div class="modal_body_cont">
          <a-form layout="inline">
            <a-form-item label="谷歌邮箱" required>
              <a-input v-model="googleEmail"  :style="{width:'400px'}" placeholder="请输入谷歌邮箱" />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script>
import {
  ClientListSearchKeys,
  ClientListColumn,
  ClientModalKeys,
  ClientExpandColumn,
  ClientGoogleListColumn
} from "./config";
import {
  clientList,
  clientUpdate,
  clientOne,
  clientActive,
  clientTemplateList,
  queryTemplateField,
  addTemplateField,editTemplateField,deleteTemplateField,searchTemplateField,
  queryGoogleAuth,bindGoogleAuth
} from "@/api/company";
import {orderTemplate,orderImport} from '@/api/order'

export default {
  name: "CompanyClient",
  data() {
    return {
      pageTitle: "",
      ClientListSearchKeys,
      ClientListColumn,
      ClientExpandColumn,
      // 高级搜索 展开/关闭
      advanced: false,
      dataSource: [],
      pagination: false,
      page: 1,
      size: 50,
      total: 0,
      loading: false,
      editVisible: false,
      searchForm: this.$form.createForm(this, { name: "client_list_search" }),
      modalForm: this.$form.createForm(this, {
        name: "client_list_modal",
      }),
      ClientModalKeys,
      clientId: "",
      sortString: "createTime,desc",
      modalType: "add",
      innerData:[],
      innerLoading:false,
      templateVisible:false,
      FieldList:[],
      onEdit: false,
      templateType:'add',
      currClientId:'',
      templateName:'',
      currTemplateId:'',
      curExpandedRowKeys:[],
      importLoading:false,
      googleVisible:false,
      googleList:[],
      ClientGoogleListColumn,
      validEmailVisible:false,
      googleEmail:''
    };
  },
  computed: {
    getDataWithKey() {
      return (key) => {
        switch (key) {
          case "status":
            return [
              { key: 1, value: "正常" },
              { key: 0, value: "禁用" },
            ];
          default:
            return [];
        }
      };
    },
  },
  created() {
    this.pageTitle = this.$route?.meta?.title;
    this.getList();
  },
  methods: {
    search() {
      this.page = 1;
      this.getList();
    },
    reset() {
      this.searchForm.resetFields();
      this.page = 1;
      this.getList();
    },
    onPageSizeChange(page, size) {
      this.page = page;
      this.getList(page, size);
    },
    async getTemplateField(){
      let res = await queryTemplateField()
      console.log('rererer',res)
      this.FieldList = res?.data
    },
    statusUpdate(record) {
      this.$confirm({
        title: `确定要${record.status == 1 ? "禁用" : "启用"}吗？`,
        content: "",
        okText: `${record.status == 1 ? "禁用" : "启用"}`,
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          clientActive({
            id: record.id,
            active: record.status == 1 ? 0 : 1,
          }).then((res) => {
            this.$message.success("操作成功");
            this.getList();
          });
        },
      });
    },
    tableSort(page, filters, { field, order }) {
      if (field == "createTime") {
        this.sortString = order
          ? field + "," + (order == "descend" ? "desc" : "asc")
          : "";
        this.getList(1);
      }
    },
    cameltoLine(value) {
      return value.replace(/([A-Z])/g, "_$1").toLowerCase();
    },
    // 获取列表
    async getList(currentPage, currentSize) {
      this.loading = true;
      const { page, size, sortString } = this;
      let sort = sortString.split(",");
      this.searchForm.validateFields(async (err, values) => {
        console.log("values :>> ", values);
        if (!err) {
          let params = {
            pageNum: currentPage || page,
            pageSize: currentSize || size,
            ...values,
            orders: [
              {
                column: this.cameltoLine(sort[0]),
                asc: sort[1] == "desc" ? false : true,
              },
            ],
            createTime:
              (values?.createTime && values?.createTime.format("YYYY-MM-DD")) ||
              "",
          };
          const res = await clientList(params);
          if (res?.success) {
            this.total = res?.data?.total || 0;
            this.dataSource = res?.data?.list || [];
          } else {
            this.$message.error(res?.message);
          }
          this.loading = false;
        } else {
          this.loading = false;
        }
      });
    },
    goSkuPrice({id}){
      this.$router.push({
        name:'CompanySkuPrice',
        query:{
          clientId:id
        }
      })
    },
    async checkGoogleAuth({id}){
      let res = await queryGoogleAuth({clientId:id})
      this.googleList = res?.data
      this.googleVisible = true
    },
    cancelGoogleEmail(){
      this.currClientId = ''
      this.googleEmail = ''
    },
    showGoogleModal({id}){
      this.currClientId = id
      this.validEmailVisible = true
    },
    async sureGoogleEmail(){
      let {currClientId,googleEmail} = this
      if(googleEmail.trim() ==''){
        this.$message.error('请输入谷歌邮箱')
        return
      }
      let res = await bindGoogleAuth({clientId:currClientId,email:googleEmail})
      if(res?.success){
        res?.data && window.open(res?.data)
      }else{
        this.$message.error(res?.message)
      }

      this.currClientId = ''
      this.googleEmail = ''
      this.validEmailVisible = false
    },
    showModal(type, record) {
      this.modalType = type;
      if (type == "add") {
        this.clientId = "";
        this.modalForm.resetFields();
        this.editVisible = true;
      } else if (type == "edit") {
        clientOne({ id: record.id }).then((res) => {
          if (res.code == 200) {
            this.editVisible = true;
            let { id, name, remark, email, status } = res.data;
            this.clientId = id;
            this.$nextTick(() => {
              this.modalForm.setFieldsValue({
                name,
                remark,
                status,
                email,
              });
            });
          } else this.$message.error(res.message);
        });
      }
    },
    sureModal() {
      let { clientId, modalType } = this;
      this.modalForm.validateFields(async (err, values) => {
        if (!err) {
          let params = {
            ...values,
            id: clientId,
          };
          clientUpdate(params).then((res) => {
            if (res?.success) {
              this.$message.success(
                `${modalType == "add" ? "添加" : "编辑"}成功`
              );
              this.clientId = "";
              this.editVisible = false;
              this.getList();
            } else {
              this.$message.error(res?.message);
            }
          });
        }
      });
    },
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    async getInnerData(expanded, {id =''}){
      this.currClientId = id
        if (this.curExpandedRowKeys.length > 0) {
          let index = this.curExpandedRowKeys.indexOf(id);
          if (index > -1) {
              this.curExpandedRowKeys.splice(index, 1);
          } else {
              this.curExpandedRowKeys.splice(0, this.curExpandedRowKeys.length);
              this.curExpandedRowKeys.push(id);
          }
      } else {
          this.curExpandedRowKeys.push(id);
      }
      if (expanded) { 
        await this.getTemplateData(id)
      }
    },
    async getTemplateData(id){
      this.innerLoading = true
      let innerRes = await clientTemplateList({clientId:id})
      this.innerData = innerRes?.data
      this.innerLoading = false
    },
    // 新增模板
    async createNewTem({id}) {
      await this.getTemplateField()
      this.templateType = 'add'
      this.currClientId = id
      this.templateVisible = true
      // orderTemplate().then((res) => {
      //   window.open(res?.data);
      // });
    },
    async sureTemplate(){
      let {templateName,currClientId,FieldList,templateType,curExpandedRowKeys} = this
      if(templateName.trim() == ''){
        this.$message.error('请输入模板名称')
        return
      }
      let params = {
        templateName,
        clientId:currClientId,
        rules: FieldList
      }
      if(templateType == 'edit'){
        params['id'] = this.currTemplateId
      }
      let res = templateType == 'add' ? await addTemplateField(params) : await editTemplateField(params), wordsTem = templateType == 'add'?'新增成功':'编辑成功'
      if(res?.success){
        this.$message.success(wordsTem)
      }else{
        this.$message.error(res?.message)
      }
      this.currClientId = ''
      this.currTemplateId = ''
      this.templateName = ''
      this.getList()
      if(curExpandedRowKeys.length>0){
        this.getTemplateData(curExpandedRowKeys[0])
      }
      this.templateVisible = false

    },
    async getCurrTemplateInfo(id){
      let res = await searchTemplateField({templateId:id})
      this.FieldList = res?.data
    },
    async editTem({id = '',templateName = ''}){
      this.templateType = 'edit'
      this.currTemplateId = id
      this.templateName = templateName
      await this.getCurrTemplateInfo(id)
      this.templateVisible = true
    },
    deleteTem(inner){
      console.log('innnd',inner)
      this.$confirm({
        title: `确定要删除该模板吗？`,
        content: "",
        okType: "danger",
        cancelText: "取消",
        onOk: () => {
          deleteTemplateField(inner.id).then((res) => {
            this.$message.success("操作成功");
            this.getList();
            if(this.curExpandedRowKeys.length>0){
              this.getTemplateData(this.curExpandedRowKeys[0])
            }
          });
        },
      });
    },

    customUploadExcel(data){
      this.importLoading = true
      let formData = new FormData()
      formData.append('file', data.file)
      formData.append('clientId', data.data.clientId)
      formData.append('templateId',data.data.templateId)
      orderImport(formData).then((res) => {
          if(res?.code == 200){
            this.$message.success('导入成功')
            this.getList()
            this.importLoading = false
          }else{
            this.$message.error(res?.message)
            this.importLoading = false
          }
      })
    },
  },
};
</script>
<style lang="less" scoped>
table.my-table, table.my-table th, table.my-table td{
    border :1px solid #e8e8e8;
    border-collapse: collapse;
  }
  table.my-table th{
    background-color:#fafafa;
  }
  table.my-table th, table.my-table td{
    padding:10px 20px;
  }
</style>
